package com.ruantong.dingtalk.ding.openapi;

import com.alibaba.fastjson.JSON;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiAttendanceListRequest;
import com.dingtalk.api.response.OapiAttendanceListResponse;
import com.ruantong.dingtalk.ding.openapi.token.DingTokenStore;
import com.ruantong.dingtalk.ding.util.DingRequestUtil;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author jh.cjh
 * @description:调用考勤的api
 * @date 2020-11-17
 */
@Component
@Slf4j
public class AttendanceApi {

    @Autowired
    private DingTokenStore dingTokenStore;

    private final static Long MAX_SIZE = 50L;

    public OapiAttendanceListResponse getUerAttnResult(LocalDateTime workDateFrom, LocalDateTime workDateTo,
                                                       List<String> idList, Long index, Long limit) {
        OapiAttendanceListResponse rsp = null;
        if (Objects.isNull(idList) || idList.size() > MAX_SIZE) {
            log.warn("method getUerAttnResult: parameter idList is Illegal!");
            return rsp;
        }
        if (limit == null || limit > MAX_SIZE) {
            log.warn("method getUerAttnResult: parameter limit is Illegal!");
            return rsp;
        }
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/attendance/list");
            OapiAttendanceListRequest req = new OapiAttendanceListRequest();
            req.setWorkDateFrom(DingRequestUtil.coverDate(workDateFrom));
            req.setWorkDateTo(DingRequestUtil.coverDate(workDateTo));
            req.setUserIdList(idList);
            req.setOffset(index * limit);
            req.setLimit(limit);
            rsp = client.execute(req, dingTokenStore.getToken());
            log.info("AttendanceList:{}", JSON.toJSONString(rsp));
        } catch (ApiException e) {
            log.error(e.getErrCode(), e.getErrMsg());
        }
        return rsp;
    }

}
